from __future__ import print_function ## a hack to enable print as a function. This MUST come as the first line.
import json
import sys
import struct
import zlib
import logging
import sys

class PuzaRow:
    def __init__(self, obj = None):
        if obj == None:
            self.__dic = {}
        elif type(obj) == dict:
            self.__dic = obj
        elif type(obj) == str:
            self.__dic = json.loads(obj)
        else:
            print('row construct failed!.')
            print(obj)
            sys.exit()
        self.__structure = {}
        
    @staticmethod
    def Load(raw_str = ''):
        r = None
        try:
            obj = json.loads(raw_str)
            r = PuzaRow(obj)
        except:
            pass
        return r
    
    def Dump(self):
        return self.__str__()
    
    def __contains__(self, k):
        return self.__getitem__(k)
    
    def __getitem__(self, k):
        s = k.split('/')
        for i in range(len(s)):
            if i == 0:
                current_holder = self.__dic
            else:
                current_holder = current_holder[s[i-1]]
            if not s[i] in current_holder:
                return None
        obj = current_holder[s[i]]
        return obj
    
    def __setitem__(self, k, v):
        s = k.split('/')
        for i in range(len(s)):
            if i == 0:
                current_holder = self.__dic
            else:
                current_holder = current_holder[s[i-1]]
            if not s[i] in current_holder:
                current_holder[s[i]] = {}
        current_holder[s[i]] = v
    
    def __str__(self):
        raw_str = json.dumps(self.__dic, sort_keys = False)
        return raw_str
    
    def __dump_dict(self, obj, parent_str, level):
        for item_name, item_value in obj.iteritems():
            current_str = parent_str + '->' + item_name
            self.__structure[current_str] = {'level':level + 1, 'type':str(type(item_value))}
            if type(item_value) == dict:
                self.__dump_dict(item_value, current_str, level + 1)
        return
    
    def GetStructure(self):
        self.__structure = {}
        self.__dump_dict(self.__dic, 'root', -1)
        return self.__structure
